<?php
class Picture extends MY_Model {

   	var $table_name = 'picture';
	var $primary_key = 'id';
	function get_list($folder_id=null,$start=null,$limit=null,$sort= '',$dir='ASC',$where = null,$fields = '*')
    {
    	$this->db->select($fields);
		$this->db->from($this->table_name);
		if(!empty($folder_id)){
			$this->db->join('folder_picture', "folder_picture.picture_id = picture.id AND folder_picture.folder_id = $folder_id");		
		}
		if(!empty($where)) $this->db->where($where);
    	if(!empty($sort)) $this->db->order_by($sort, $dir);
    	elseif(!empty($folder_id))	$this->db->order_by('folder_picture.order', 'ASC');
    	else $this->db->order_by("{$this->table_name}.order", 'ASC');
    	if(!empty($limit)) $this->db->limit($limit,$start);
	    $query = $this->db->get();
		return $query->result_array();        
    }
	function get_total($folder_id=null)
    {
		$this->db->from($this->table_name);
		if(!empty($folder_id))$this->db->join('folder_picture', "folder_picture.picture_id = {$this->table_name}.{$this->primary_key} AND folder_picture.folder_id = $folder_id");
		return $this->db->count_all_results();
    }
	function get_max(){
		$query = $this->db->query("SELECT MAX(`order`) as max_order FROM `{$this->table_name}`");
		$row = $query->row_array();
        return $row['max_order'];	
	}
	function update($data,$id)
    {
		$this->filterData($data);
		$curr = $this->get_by_id($id);
		if(array_key_exists('order', $data)&&$curr['order']>$data['order']){
			$sub = $curr['order']-1;
			$this->db->query("UPDATE {$this->table_name} SET `order` = `order` + 1 WHERE `order` BETWEEN {$data['order']} AND $sub");
		}elseif(array_key_exists('order', $data)&&$curr['order']<$data['order']){
			$inf = $curr['order']+1;
			$this->db->query("UPDATE {$this->table_name} SET `order` = `order` - 1 WHERE `order` BETWEEN  $inf AND {$data['order']}");
		}
		return $this->db->update($this->table_name, $data, array($this->primary_key => $id));
    }
	function delete($id){
		$curr = $this->get_by_id($id);
		$this->db->query("UPDATE {$this->table_name} SET `order` = `order` - 1 WHERE `order` > {$curr['order']}");
    	return $this->db->delete($this->table_name, array($this->primary_key => $id)); 
    }
}